package com.qgz.framework.web.config;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ActionContainer {
	Logger log = Logger.getLogger(ActionContainer.class);

	private static ActionContainer container;

	private Map<String, ActionConfig> actionMap;

	private String configFilePath;

	public static ActionContainer init(String file) {
		try {
			if (container == null) {
				container = new ActionContainer(file);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return container;

	}

	public static ActionContainer getInstance() {
		return container;
	}

	public ActionConfig getAction(String path) {
		return this.getActionMap().get(path);
	}

	public String print() {
		StringBuffer result = new StringBuffer();
		Iterator<String> key = this.getActionMap().keySet().iterator();
		while (key.hasNext()) {
			result.append("======================================\r\n");
			String path = key.next();
			ActionConfig temp = this.getActionMap().get(path);
			result.append("path:").append(temp.getPath()).append("\r\n");
			result.append("method:").append(temp.getMethod()).append("\r\n");
			result.append("class:").append(temp.getClassName()).append("\r\n");
			result.append("result:").append("\r\n");
			Iterator<String> resultKey = temp.getResultMap().keySet()
					.iterator();
			while (resultKey.hasNext()) {
				String name = resultKey.next();
				result.append("    ").append(name).append(":").append(
						temp.getResult(name)).append("\r\n");
			}
		}
		return result.toString();
	}

	public String getConfigFilePath() {
		return configFilePath;
	}

	public void setConfigFilePath(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	public Map<String, ActionConfig> getActionMap() {
		return actionMap;
	}

	public void setActionMap(Map<String, ActionConfig> actionMap) {
		this.actionMap = actionMap;
	}

	private ActionContainer(String path) {
		actionMap = new HashMap<String, ActionConfig>();
		this.setConfigFilePath(path);

		try {
			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dombuilder = domfac.newDocumentBuilder();
			Document doc = dombuilder.parse(new File(this.getConfigFilePath()));

			Element root = doc.getDocumentElement();

			NodeList nodes = root.getElementsByTagName(ActionConfig.TAG_ACTION
					.toLowerCase());
			for (int i = 0; i < nodes.getLength(); i++) {
				Node temp = nodes.item(i);
				ActionConfig tempConfig = new ActionConfig();

				Node actionPath = temp.getAttributes().getNamedItem(
						ActionConfig.TAG_PATH.toLowerCase());
				if (actionPath == null) {
					throw new RuntimeException("action path can not be none.");
				}
				tempConfig.setPath(actionPath.getNodeValue());

				Node actionMethod = temp.getAttributes().getNamedItem(
						ActionConfig.TAG_METHOD.toLowerCase());
				if (actionMethod == null) {
					log.debug("action method is none,use default method.");
				}
				tempConfig.setMethod(ActionConfig.DEFAULT_METHOD);

				Node actionClass = temp.getAttributes().getNamedItem(
						ActionConfig.TAG_CLASS.toLowerCase());
				if (actionClass == null) {
					tempConfig.setClassName("com.qgz.framework.web.DirectWebAction");
				}else{
					tempConfig.setClassName(actionClass.getNodeValue());
				}				

				NodeList results = temp.getChildNodes();

				for (int p = 0; p < results.getLength(); p++) {
					if (!ActionConfig.TAG_RESULT.toLowerCase().equals(
							results.item(p).getNodeName())) {
						continue;
					}
					ResultConfig result = new ResultConfig();
					result.setName(results.item(p).getAttributes()
							.getNamedItem(ActionConfig.TAG_NAME.toLowerCase())
							.getNodeValue());
					result.setValue(results.item(p).getFirstChild()
							.getNodeValue());
					tempConfig.setResult(result.getName(), result.getValue());

				}
				actionMap.put(tempConfig.getPath(), tempConfig);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
